import { useRef, RefObject, useContext, useState, useEffect } from 'react'
import { PDFSignSchema } from '@src/components/schema/pdf'
import { Modal, Form, FormInstance, Select, Input, message } from 'antd';
import { CaseSchema, PartySchema } from '@src/components/schema/caseSchema';
import { ArbitratorSchema } from '@src/components/schema/arbitrator';
import { ParticipantSchema } from '@src/components/schema/videoCourt';
import { SignContext } from '../../../../../context';
import { awaitWrap } from '@src/assets/js/tool';
import { addRequest } from './ajax';

const { Item } = Form
const { Option } = Select
const types = ['申请人', '申请人代理人', '被申请人', '被申请人代理人', '仲裁员', '仲裁秘书', '其他']

// 改变仲裁地位
function changeType (
  v: string,
  formRef: RefObject<FormInstance>,
  data: CaseSchema | null,
  arbitrators: ArbitratorSchema[],
  otherPersonList: ParticipantSchema[],
  setPersonList: (v: PartySchema[]) => void,
  setType: (v: string) => void
) {
  const c = formRef.current
  if (!c) {
    return undefined
  }
  c.resetFields()
  c.setFieldsValue({
    action_subject: v
  })
  if (data === null) {
    return undefined
  }
  let personList: PartySchema[] = []
  if (v === '申请人') {
    personList = data.applicants.filter(li => li.status && li.subject_type === '自然人')
  } else if (v === '被申请人') {
    personList = data.respondents.filter(li => li.status && li.subject_type === '自然人')
  } else if (v === '申请人代理人') {
    personList = data.applicant_agents || []
  } else if (v === '被申请人代理人') {
    personList = data.respondents_agents || []
  } else if (v === '仲裁员') {
    personList = arbitrators as unknown as PartySchema[]
  } else if (v === '仲裁秘书') {
    initFormByPerson(v, {id: data.processerid, name: data.processer, mobile: data.processer_mobile}, formRef)
  } else {
    personList = otherPersonList as unknown as PartySchema[]
  }
  setPersonList(personList)
  setType(v)
}

// 根据人员信息初始化表单数据
function initFormByPerson (t: string, d: {[k: string]: any}, formRef: RefObject<FormInstance>) {
  const c = formRef.current
  const form: {[k: string]: any} = { name: d.name, mobile: d.mobile || '', bizid: d.id }
  if (c) {
    c.setFieldsValue(form)
  }
}

// 渲染姓名项
function renderNameItem (t: string, personList: PartySchema[], formRef: RefObject<FormInstance>) {
  const p = personList
  if (['申请人', '申请人代理人', '被申请人', '被申请人代理人', '仲裁员', '其他'].indexOf(t) !== -1) {
    return (
      <Select placeholder='请选择人员' onChange={v => changeName(t, v, personList, formRef)}>
        {p.map((li, i) => <Option key={i} value={li.id}>{li.name}</Option>)}
      </Select>
    )
  }
  return <Input placeholder='请输入姓名' disabled={t === '仲裁秘书'} />
}

// 选择人员
function changeName (t: string, id: string, l: PartySchema[], formRef: RefObject<FormInstance>) {
  let o = null
  for (let i = 0; i < l.length; i++) {
    if (l[i].id === id) {
      o = l[i]
      break
    }
  }
  if (!o) {
    return false
  }
  initFormByPerson(t, o, formRef)
}

async function addHandle ( data: { [k: string]: any }, caseid: string, documentid: string, refreshFn: () => void) {
  data.caseid = caseid
  data.documentid = documentid
  const h = message.loading('提交中', 120)
  data.locationy = document.documentElement.scrollTop / 1131
  const [e] = await awaitWrap(addRequest(data))
  h()
  if (e === null) {
    refreshFn()
  }
}

interface Props {
  data: PDFSignSchema | null
  caseid: string
  documentid: string
  visible: boolean
  hide: () => void
  refreshFn: () => void
}

function Main ({ data, visible, caseid, documentid, hide, refreshFn }: Props) {
  const formRef = useRef<FormInstance>(null)
  const c = useContext(SignContext)
  const [personList, setPersonList] = useState<PartySchema[]>([])
  const [t, setT] = useState('')
  useEffect(() => {
    const current = formRef.current
    if (!visible && current) {
      current.resetFields()
    }
  }, [visible])
  return (
    <div>
      <Modal
        title='添加签名信息'
        visible={visible}
        maskClosable={false}
        onCancel={() => hide()}
        onOk={() => formRef.current?.submit()}
      >
        <Form ref={formRef} labelCol={{ flex: '88px' }} onFinish={d => { addHandle(d, caseid, documentid, () => { hide(); refreshFn() }) }}>
          <Item noStyle name='bizid'><span /></Item>
          <Item name='action_subject' label='仲裁地位' rules={[{ required: true, message: '仲裁地位不能为空' }]}>
            <Select placeholder='请选择仲裁地位' onChange={v => changeType(v, formRef, c.caseDetail, c.arbitrators, c.otherPersons, setPersonList, setT)}>
              {types.map((li, i) => <Option key={i} value={li}>{li}</Option>)}
            </Select>
          </Item>
          <Item name='name' label='姓名' rules={[{ required: true, message: '姓名不能为空' }]}>
            {renderNameItem(t, personList, formRef)}
          </Item>
          <Item name='mobile' label='手机号' rules={[{ required: true, message: '手机号不能为空' }]}>
            <Input placeholder='请输入手机号' maxLength={11} disabled />
          </Item>
        </Form>
      </Modal>
    </div>
  )
}

export default Main
